package com.medistat.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.primefaces.event.DateSelectEvent;
import org.springframework.beans.factory.annotation.Autowired;

import com.medistat.dialog.Schedule;
import com.medistat.model.FreeDay;
import com.medistat.reports.ScheduleExcelExporter;
import com.medistat.util.DateUtils;

public abstract class ScheduleController extends AbstractController {

	//state 
	private List<Schedule> schedules = new ArrayList<Schedule>();
	private List<FreeDay> freeDays = new ArrayList<FreeDay>();
	private Date dateFrom;
	private Date dateUntil;
	
	//service
	private ScheduleExcelExporter scheduleExcelExporter;
	
	@Autowired
	public void setScheduleExcelExporter(ScheduleExcelExporter scheduleExcelExporter) {
		this.scheduleExcelExporter = scheduleExcelExporter;
	}

	public List<Schedule> getSchedules() {
		return schedules;
	}

	public void setSchedules(List<Schedule> schedules) {
		this.schedules = schedules;
	}
	
	public List<FreeDay> getFreeDays() {
		return freeDays;
	}

	public void setFreeDays(List<FreeDay> freeDays) {
		this.freeDays = freeDays;
	}

	public Date getDateFrom() {
		if(dateFrom!=null) {
			dateFrom = DateUtils.getMinDate(dateFrom);
		}
		return dateFrom;
	}

	public void setDateFrom(Date dateFrom) {
		this.dateFrom = dateFrom;
	}

	public Date getDateUntil() {
		if(dateFrom!=null) {
			dateUntil = DateUtils.getMaxDate(dateFrom);
		}
		return dateUntil;
	}

	public void setDateUntil(Date dateUntil) {
		this.dateUntil = dateUntil;
	}
	
	public void handleDateSelect(DateSelectEvent event) {
		//needed because of handling dates on page - DO NOT REMOVE!
	}
	
	public void showFreeDays() {
		List<FreeDay> freeDays = null;
		try {
			Calendar dateFrom = DateUtils.convertDateToCalendar(getDateFrom());
			Calendar dateUntil = DateUtils.convertDateToCalendar(getDateUntil());
			freeDays = getDialogService().getFreeDays(dateFrom, dateUntil);
		} catch(AssertionError e) {
			addError(e.getMessage());
		} catch (Exception e) {
			addWarning(e.getMessage());
		}
		setFreeDays(freeDays);
	}
	
	public void clearSchedule() {
		if(getSchedules()==null) {
			return;
		}
		getSchedules().clear();
		clearFreeDays();
	}
	
	public void clearFreeDays() {
		if(getFreeDays()==null) {
			return;
		}
		getFreeDays().clear();
	}
	
	public void exportWithPoi() throws IOException {
		scheduleExcelExporter.export(getSchedules());
   }
}
